import common from './common'

import { proxyUrl } from '../../libs/util'

/**
 * 重置大小
 * @returns {{x: number, y: number, width: number, height: number, rotate: number}}
 */
const resetSize = () => ({
  x: 0,
  y: 0,
  width: 0,
  height: 0,
  rotate: 0
})
/**
 * 计算大小
 * @param current
 */
const calculateSize = (current) => {
  let size = {...resetSize(), ...current}
  if (size.rotate > 0 && size.width > 0) {
    if (size.cx === undefined) size.cx = size.width / 2
    if (size.cy === undefined) size.cy = size.height / 2
  }
  size.href = proxyUrl(size.href, true)
  return size
}

const handleMethods = {}

const ImageHandler = {
  name: 'image-handler',
  props: {
    id: String,               // 编号
    value: {                   // 定位、宽高
      type: Object,
      default: resetSize
    }
  },
  data () {
    return {
      current: calculateSize(this.value)
    }
  },
  computed: {},
  watch: {
    value: {
      handler (size, oldVal) {
        this.current = calculateSize(size)
      },
      deep: true
    }
  },
  render (h) {
    const shape = this.current
    const viewBox = `0 0 ${shape.width} ${shape.height}`
    return (
      <g transform={common.matrix(shape)} data-type="image" className="parentGroup" style="opacity: 1;">
        <svg width={shape.width} height={shape.height} viewBox={viewBox} style={shape.style}>
          <defs></defs>
          <rect width={shape.width} height={shape.height} opacity="0" className="imageRect"/>
          <g className="imageGroup">
            <image href={shape.href} width={shape.width} height={shape.height} x={0} y={0}/>
          </g>
        </svg>
      </g>
    )
  },
  methods: {
    ...handleMethods
  }
}

export default ImageHandler
